// startColor：开始颜色hex
// endColor：结束颜色hex
// step:几个阶级（几步）
export function gradientColors(start, end, steps, gamma) {
  let i, j, ms, me
  const output = [], so = [];
  gamma = gamma || 1;
  const normalize = function (channel) {
    return Math.pow(channel / 255, gamma);
  };
  start = parseColor(start).map(normalize);
  end = parseColor(end).map(normalize);
  for (i = 0; i < steps; i++) {
    ms = i / (steps - 1);
    me = 1 - ms;
    for (j = 0; j < 3; j++) {
      so[j] = pad(Math.round(Math.pow(start[j] * me + end[j] * ms, 1 / gamma) * 255).toString(16));
    }
    output.push('#' + so.join(''));
  }
  return output;
}

function parseColor(hexStr) {
  return hexStr.length === 4 ? hexStr.substr(1).split('').map(function (s) { return 0x11 * parseInt(s, 16); }) : [hexStr.substr(1, 2), hexStr.substr(3, 2), hexStr.substr(5, 2)].map(function (s) { return parseInt(s, 16); })
}

// zero-pad 1 digit to 2
function pad(s) {
  return (s.length === 1) ? '0' + s : s;
}

/**
 *
 * @param sColor #F00/#FF0000
 * @param opacity 透明度
 */
export function color2rgba(sColor, opacity = 1) {
  const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
  sColor = sColor.toLowerCase()

  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      let sColorNew = '#';
      for (let i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
      }
      sColor = sColorNew
    }
    // 处理六位的颜色值
    const sColorChange = []
    for (let i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)));
    }
    sColorChange.push(opacity)
    const str = sColorChange.join(',');
    return 'rgba(' + str + ')'
  } else {

    return sColor;
  }

}

